$(function () {
    /**
     * $search.key   标签KEY
     * $search.value 标签值
     * $search.label 标签名称
     */
    var
        $search = parseSearch(),
        tag = ''
    ;
    $search.label = $search.label || '';

    var arg = { // 多分类匹配
        query: '/category/list?type1=' + $search.value,//分页查询URL,
        rendered: function () {
            if ($search.rmBtn) {
                $search.rmBtn.split(',').map(function (btn) {
                    if (btn == 'add') {
                        btns[0].remove();
                    }
                    if (btn == 'rm') {
                        btns[2].remove();
                    }
                })
            }
            $('.category-detail').each(function (index, item) {
                var $item = $(item);
                // onClick($('.category-detail'),function (e) {
                //     e.stopPropagation();
                var id = $item.data().id;
                // var that = this;
                $.get('/category/listDRBySourceId?targetId=' + id + '&type1=shop-category&dataRtype1=shop-category', function (res) {
                    console.log(res);
                    if (res.list && res.list.list) {
                        if (res.list.list.length != 0) {
                            $item.replaceWith('<span>' + _.pluck(res.list.list, 'name').join(',') + '<span>')
                        } else {
                            $item.replaceWith('<span>无<span>')
                        }
                    }
                })
            })
            if (window.categoryId && !$('[name=categoryId]').data('init')) {//
                var filterObj = lsGet(opt.lastSearchKey);
                getClassifiedQuery({url: '/category/listSummary?type1=31&size=10000'}, function (res) {
                    var categorys2 = res
                    selectpickerFn({
                        ele: $('[name=categoryId]'),
                        name: 'categoryId',
                        label: '请选择分类',
                        placeholder: '所有分类',
                        selected: categorys2.id || '',
                        list: categorys2,
                        change: function (id) {
                            console.log(id);
                            $('[name=categoryId]').val(id);
                            search({categoryId: id, page: 1}, true)
                        }
                    })
                })
            }
        },
        btns: [
            {
                label: '增加' + $search.label,
                class_: 'create',
                onClick: function () {
                    var $index = dialogForm(
                        {
                            title: '增加' + $search.label,
                            data: [
                                {
                                    type: 'text',
                                    label: '名称',
                                    require: true, // 是否必填
                                    placeholder: '请输入名称',
                                    name: 'name'
                                },
                                {
                                    type: 'textarea',
                                    label: '描述',
                                    val: '',
                                    require: true, // 是否必填
                                    placeholder: '请输入描述',
                                    name: 'desc1'
                                },

                                {
                                    type: 'text',
                                    label: '排序号',
                                    val: '0',
                                    placeholder: '请输入排序号',
                                    name: 'orderNum'
                                },
                            ],
                            submit: function (form) {
                                form.type1 = $search.value; // 数据类型菜单
                                $.post('/category/add', form, function (res) {
                                    if (res.code == 200) {
                                        fnSuccess("操作成功");
                                        search({}, true);
                                        closeLayer($index);
                                    } else {
                                        fnFail("操作失败");
                                    }
                                })
                            }
                        });
                }
            },
            {
                label: '修改' + $search.label,
                class_: 'update',
                onClick: function () {
                    var $json = $(this).data('json');
                    var $index = dialogForm(
                        {
                            title: "修改" + $search.label,
                            data: [
                                {
                                    type: 'text',
                                    label: '名称',
                                    val: $json.name,
                                    require: true, // 是否必填
                                    placeholder: '请输入名称',
                                    name: 'name'
                                },
                                {
                                    type: 'textarea',
                                    label: '描述',
                                    val: $json.desc1,
                                    require: true, // 是否必填
                                    placeholder: '请输入描述',
                                    name: 'desc1'
                                },

                                {
                                    type: 'text',
                                    label: '排序号',
                                    val: $json.orderNum,
                                    placeholder: '请输入排序号',
                                    name: 'orderNum'
                                },
                            ],
                            submit: function (form) {
                                form.id = $json.id; // 数据类型菜单
                                form.type1 = $search.value; // 数据类型菜单
                                $.post('/category/update', form, function (res) {
                                    if (res.code == 200) {
                                        fnSuccess("操作成功");
                                        search({}, true);
                                        closeLayer($index);
                                    } else {
                                        fnFail("操作失败");
                                    }
                                })
                            }
                        });
                }
            },
            {
                label: '删除',
                class_: 'delete',
                onClick: function () {
                    var $json = $(this).data('json');
                    console.log($json);
                    if (confirm('确认删除？')) {
                        $.post('/category/delete/' + $json.id, {}, function (res) {
                            if (res.code == 200) {
                                search({}, true);
                                fnSuccess('删除成功！');
                            }
                        })
                    }
                }
            },
            {
                label: '上架/下架',
                class_: 'update',
                onClick: function () {
                    var $jon = $(this).data('json');
                    var $json = {};
                    var ti = [
                        'targetId=' + $jon.id,
                        'type1=' + ($search.value),
                        'isShow=' + ($jon.isShow == '1' ? '0' : '1')
                    ];
                    $.get('/statistic1/set?' + ti.join('&'), function (res) {
                        if (res.code == 200) {
                            search({}, true);
                        }
                    })
                }
            },
            {
                label: '图片选择器',
                class_: 'upload select-from-libs',
                // onClick: function () {
                //     var $json = $(this).data('json');
                //     uploadFn('上传图片', {
                //         w: $search.w || 100,
                //         h: $search.h || 100,
                //         num: 12,
                //         labelNum: 12 + ' upload-custom-label',
                //         noCrop: !!$search.nocrop,
                //         preview: 'left-top-preview'
                //     }, function (data) {
                //         closeLayer(data.layerIndex);
                //         $.post('/category/update', {id: $json.id, url: data.path}, function (res) {
                //             if (res.code == 200) {
                //                 fnSuccess('上传成功～');
                //                 search({}, true)
                //             } else {
                //                 fnFail(res.error || '上传失败！')
                //             }
                //         })
                //     });
                // },
                /**
                 * 从图片库中选择
                 */

                onClick:function () {
                imageSelector({
                    multi: true,
                    title: '',
                    body: $('#imgs').html()
                }, {
                    ok: function (arr, cb, t) {
                        arr = arr || [];
                        arr.map(function (item) {
                            initImg(item.url, false, item.id)
                            cb(t)
                        })
                    },
                    cancel: function (cb, t) {
                        cb(t)
                    },
                    dbclick: function ($ele) {
                        $ele.find('img.appendImg').attr('src')
                        $ele.find('img.appendImg').attr('id')

                    },
                    click: function ($ele) {
                        $ele.find('img.appendImg').attr('src')
                        $ele.find('img.appendImg').attr('id')
                    }
                })
            }
            }
        ],
        destroyBtn: function () {
            disableBtn(btns[3]);
            disableBtn(btns[2]);
            disableBtn(btns[1]);
            disableBtn(btns[4]);

        },
        createBtn: function (_this) {
            var $item = $(_this).data('json');
            enableBtn(btns[1], $item);
            enableBtn(btns[2], $item);
            enableBtn(btns[3], $item);
            enableBtn(btns[4], $item);

        },
        fields: [
            {name: 'name', label: '名称', enableSearch: true},
            {
                name: 'desc1', label: '描述',
                filter: function (item) {
                    return viewMore(item.desc1 || ''); // 预览更多内容
                }
            },
            {
                name: 'desc1', label: '图片',
                filter: function (item) {
                    if (item.url) {
                        return '<a ' +
                            'target="_blank" ' +
                            'style="display:inline-block;" ' +
                            'href="' + item.url + '" title="点击预览">' +
                            '<img ' +
                            'style="height:60px;border-radius: 5px" ' +
                            'src="' + item.url + '"></a>'
                    } else {
                        return getDefaultImgStr();
                    }
                }
            },
            {
                name: 'isShow', label: '上架状态',
                filter: function (item) {
                    return item.isShow == 1 ? "<span class='label label-success'>上架</span>" : "<span class='label label-warning'>下架</span>"
                },
            },
            {name: 'orderNum', label: '排序号'},
            {name: 'categoryId', label: '分类', enableSearch: true,filter: function (item) {
                    return '<a href="javascript:void(0)" ' +
                        '' +
                        'data-id="' + item.id + '" class="category-detail">查看</a>'}},
        ],
    };

    window.btns = arg.btns.map(function (item) { // 设置分类
        var btn = genBtn(item);
        if (item.onClick) onClick(btn, item.onClick)
        return btn;
    });
    setBtn(btns);

    function search(obj, isForce, isExport) {
        arg.destroyBtn();
        return gSearch({
            table: '.table',
            url: arg.query,
            query: obj,
            isForce: isForce,
            isExport: isExport,
            render: function (res) {
                var _$table = $('.table-responsive .table');
                destroyBtn();
                if (!!arg.beforeRender) res = arg.beforeRender(res);
                _$table.$table($.extend(TABLE_SETTING, {
                    checkbox: true, // 是否显示复选框
                    seqNum: true, // 是否显示序号
                    sort: search, //排序回调函数
                    destroyBtn: arg.destroyBtn, //禁用按钮
                    createBtn: arg.createBtn, // 启用她扭
                    toolbar: '.toolbar',
                    enableSetting: true,//允许自定义显示列
                    search: search,
                    showSearchComplex: true,
                    rendered: arg.rendered || function () {
                    },
                    fields: arg.fields,
                    data: arg.listFilter ? arg.listFilter(res) : res || [],
                }, arg.dateSearch ? { // 允许日期区间搜索
                    complexItems: [
                        {label: "", name: 'date', dateRange: true},
                    ]
                } : {}));
            }
        }, obj.first ? false : true);
    }

    search({}, true);
    function initImg(url, isThumbnail, fileId) {
        var item = ejs.render($('#img-item-template').html(), {
            url: url,
            isThumbnail: isThumbnail,
            id: fileId,
        });

        $(item).insertBefore($('.item-trigger').closest('.col-sm-4'));
    }
    selectGoodsClass()
    function selectGoodsClass() {
        if ($search.id) {
            $.get('/dataR/selectBy?type1=shop-category&targetId=' + $search.id, function (res) {
                $sourceId = _.pluck(res.list, 'sourceId');
                generateCategory($sourceId);
            })
        } else {
            generateCategory();
        }

        function generateCategory(categoryId) {
            getClassifiedQuery({url: '/category/listSummary?type1=31&size=10000'}, function (res) {
                var categorys2 = res
                selectpickerFn({
                    multiple: true,
                    ele: $('[name=categoryId]'),
                    name: 'categoryId',
                    label: '请选择分类',
                    placeholder: '所有分类',
                    selected: categoryId || '',
                    list: categorys2,
                    change: function (id) {
                        console.log(id);
                        $('[name=categoryId]').val(id);
                    }
                })
            })
        }
    }

})

